import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'dart:developer' as developer;
import 'permission_service.dart';
import 'storage_service.dart';

/// 高德地图定位结果数据模型
class AmapLocationResult {
  final bool success;
  final double? latitude;
  final double? longitude;
  final double? accuracy;
  final double? altitude;
  final double? bearing;
  final double? speed;
  final int? timestamp;
  final String? address;
  final String? country;
  final String? province;
  final String? city;
  final String? district;
  final String? street;
  final String? streetNumber;
  final String? poiName;
  final String? aoiName;
  final String? provider;
  final int? locationType;
  final int? errorCode;
  final String? errorMessage;

  AmapLocationResult({
    required this.success,
    this.latitude,
    this.longitude,
    this.accuracy,
    this.altitude,
    this.bearing,
    this.speed,
    this.timestamp,
    this.address,
    this.country,
    this.province,
    this.city,
    this.district,
    this.street,
    this.streetNumber,
    this.poiName,
    this.aoiName,
    this.provider,
    this.locationType,
    this.errorCode,
    this.errorMessage,
  });

  factory AmapLocationResult.fromMap(Map<String, dynamic> map) {
    return AmapLocationResult(
      success: map['success'] ?? false,
      latitude: map['latitude']?.toDouble(),
      longitude: map['longitude']?.toDouble(),
      accuracy: map['accuracy']?.toDouble(),
      altitude: map['altitude']?.toDouble(),
      bearing: map['bearing']?.toDouble(),
      speed: map['speed']?.toDouble(),
      timestamp: map['timestamp']?.toInt(),
      address: map['address'],
      country: map['country'],
      province: map['province'],
      city: map['city'],
      district: map['district'],
      street: map['street'],
      streetNumber: map['streetNumber'],
      poiName: map['poiName'],
      aoiName: map['aoiName'],
      provider: map['provider'],
      locationType: map['locationType']?.toInt(),
      errorCode: map['errorCode']?.toInt(),
      errorMessage: map['errorMessage'],
    );
  }

  @override
  String toString() {
    if (success) {
      return 'AmapLocationResult(success: $success, lat: $latitude, lng: $longitude, address: $address, accuracy: ${accuracy}m)';
    } else {
      return 'AmapLocationResult(success: $success, errorCode: $errorCode, errorMessage: $errorMessage)';
    }
  }
}

/// 高德地图定位服务类（Flutter端）
/// 
/// 🎯 统一管理 App 的位置信息：
/// - 权限检查和申请
/// - 位置获取和缓存
/// - 默认位置管理
/// - 位置状态管理
class AmapLocationService extends GetxService {
  static AmapLocationService get to => Get.find();
  
  // Platform Channel
  static const MethodChannel _channel = MethodChannel('com.playtruly.amap_location');
  static const String _latitudeStorageKey = 'user_latitude';
  static const String _longitudeStorageKey = 'user_longitude';
  static const String _locationTextStorageKey = 'user_location_text';
  
  // 🔥 权限服务依赖
  late PermissionService _permissionService;
  StorageService? _storageService;
  
  // 🔥 添加标志位：记录高德SDK是否已完成隐私合规初始化
  bool _isAmapPrivacyInitialized = false;
  
  // ==================== 📍 位置信息状态管理 ====================
  
  /// 当前位置文本（用于UI显示）
  RxString currentLocationText = '未定位'.obs;  // 🔥 初始显示"未定位"
  
  /// 当前纬度
  RxDouble currentLatitude = 39.9042.obs;  // 默认：北京天安门
  
  /// 当前经度
  RxDouble currentLongitude = 116.4074.obs;  // 默认：北京天安门
  
  /// 定位是否成功
  RxBool isLocationSuccess = false.obs;
  
  /// 定位状态
  RxBool isLocationStarted = false.obs;
  RxBool isLocating = false.obs;
  
  /// 最后一次定位结果
  Rx<AmapLocationResult?> lastLocationResult = Rx<AmapLocationResult?>(null);
  
  // ==================== 🏠 默认位置配置 ====================
  
  /// 默认城市名称（仅用于坐标，UI显示"未定位"）
  static const String defaultCityName = '未定位';
  
  /// 默认纬度（北京天安门）
  static const double defaultLatitude = 39.9042;
  
  /// 默认经度（北京天安门）
  static const double defaultLongitude = 116.4074;

  /// 🔐 初始化高德地图隐私合规（必须在用户同意隐私政策后调用）
  /// 
  /// 这是合规要求的关键步骤：
  /// 1. 用户同意隐私政策
  /// 2. 调用此方法初始化高德SDK
  /// 3. 才能使用定位服务
  Future<bool> initAmapPrivacy() async {
    try {
      developer.log('🔐 =============== 初始化高德SDK隐私合规 ===============', name: 'AmapLocationService');
      
      // 防止重复初始化
      if (_isAmapPrivacyInitialized) {
        developer.log('⚠️ 高德SDK隐私合规已初始化，跳过重复初始化', name: 'AmapLocationService');
        return true;
      }
      
      // 调用原生方法初始化高德SDK隐私合规
      final result = await _channel.invokeMethod('initAMapPrivacy');
      
      developer.log('📨 原生返回结果: $result', name: 'AmapLocationService');
      developer.log('📊 结果类型: ${result.runtimeType}', name: 'AmapLocationService');
      
      // 🔥 兼容多种返回格式
      bool success = false;
      String? message;
      
      if (result is Map) {
        // 转换为Map<String, dynamic>
        final resultMap = Map<String, dynamic>.from(result);
        success = resultMap['success'] == true;
        message = resultMap['message']?.toString();
        
        developer.log('📊 解析结果: success=$success, message=$message', name: 'AmapLocationService');
      } else if (result is bool) {
        success = result;
        developer.log('📊 直接返回布尔值: $success', name: 'AmapLocationService');
      }
      
      if (success) {
        _isAmapPrivacyInitialized = true;
        developer.log('✅ 高德SDK隐私合规配置完成', name: 'AmapLocationService');
        developer.log('✅ 现在可以安全地使用高德定位服务了', name: 'AmapLocationService');
        return true;
      } else {
        developer.log('❌ 高德SDK隐私合规配置失败: ${message ?? "未知错误"}', name: 'AmapLocationService');
        developer.log('⚠️ 原始返回数据: $result', name: 'AmapLocationService');
        return false;
      }
      
    } catch (e) {
      developer.log('💥 初始化高德SDK隐私合规异常: $e', name: 'AmapLocationService');
      return false;
    } finally {
      developer.log('🏁 ===============================================', name: 'AmapLocationService');
    }
  }

  @override
  void onInit() {
    super.onInit();
    developer.log('🗺️ =============== AmapLocationService 初始化开始 ===============', name: 'AmapLocationService');
    
    // 🔥 获取权限服务依赖
    _permissionService = Get.find<PermissionService>();
    developer.log('✅ 权限服务依赖注入成功', name: 'AmapLocationService');
    
    // 💾 注入存储服务（用于缓存上次定位结果）
    if (Get.isRegistered<StorageService>()) {
      _storageService = Get.find<StorageService>();
      developer.log('✅ 存储服务依赖注入成功', name: 'AmapLocationService');
    } else {
      developer.log('⚠️ 未找到 StorageService，无法缓存位置信息', name: 'AmapLocationService');
    }
    
    // 🏠 优先恢复上次定位结果，失败时才回退到默认位置
    final restoredFromCache = _restoreCachedLocation();
    if (!restoredFromCache) {
      _setDefaultLocation();
    }
    
    developer.log('📱 Platform Channel 名称: ${_channel.name}', name: 'AmapLocationService');
    developer.log('🔧 初始状态: isLocationStarted=${isLocationStarted.value}, isLocating=${isLocating.value}', name: 'AmapLocationService');
    developer.log('📍 默认位置: $currentLocationText ($currentLatitude, $currentLongitude)', name: 'AmapLocationService');
    developer.log('⏳ 等待用户同意隐私政策后初始化高德SDK...', name: 'AmapLocationService');
    developer.log('🗺️ =============== AmapLocationService 初始化完成 ===============', name: 'AmapLocationService');
  }

  @override
  void onClose() {
    // 确保服务关闭时停止定位
    stopLocation();
    super.onClose();
    developer.log('🗑️ AmapLocationService 已关闭', name: 'AmapLocationService');
  }
  
  // ==================== 🎯 统一定位方法（供外部调用） ====================
  
  /// 🎯 智能定位（统一入口方法）
  /// 
  /// 自动处理权限检查 → 定位 → 更新状态
  /// 外部页面只需调用此方法即可完成定位
  /// 
  /// [forceRefresh] 是否强制刷新（忽略缓存）
  /// [showRationale] 是否显示权限说明
  Future<bool> smartLocation({
    bool forceRefresh = false,
    bool showRationale = true,
  }) async {
    try {
      developer.log('🎯 =============== 开始智能定位 ===============', name: 'AmapLocationService');
      developer.log('🔧 参数: forceRefresh=$forceRefresh, showRationale=$showRationale', name: 'AmapLocationService');
      
      // 🔥 检查是否正在定位（避免重复请求）
      if (isLocating.value && !forceRefresh) {
        developer.log('⚠️ 定位请求正在进行中，忽略重复请求', name: 'AmapLocationService');
        return false;
      }
      
      // 🔒 步骤1: 检查并申请权限
      developer.log('🔒 步骤1: 检查位置权限...', name: 'AmapLocationService');
      final permissionResult = await _permissionService.requestLocationPermission(
        showRationale: showRationale,
      );
      
      if (!permissionResult.isGranted) {
        developer.log('❌ 位置权限被拒绝: ${permissionResult.message}', name: 'AmapLocationService');
        currentLocationText.value = '未定位';
        isLocationSuccess.value = false;
        developer.log('📍 使用默认位置: $currentLocationText ($currentLatitude, $currentLongitude)', name: 'AmapLocationService');
        return false;
      }
      
      developer.log('✅ 位置权限已授权', name: 'AmapLocationService');
      
      // 📍 步骤2: 执行定位
      developer.log('📍 步骤2: 开始高德定位...', name: 'AmapLocationService');
      currentLocationText.value = '定位中...';
      isLocating.value = true;  // 🔥 设置定位状态
      
      final locationResult = await startLocation(
        isOnceLocation: true,
        timeout: const Duration(seconds: 15),
      );
      
      if (locationResult != null && locationResult.success) {
        // 🎉 定位成功
        developer.log('✅ 定位成功!', name: 'AmapLocationService');
        await _updateLocationFromResult(locationResult);
        return true;
      } else {
        // ❌ 定位失败
        developer.log('❌ 定位失败: ${locationResult?.errorMessage ?? "未知错误"}', name: 'AmapLocationService');
        currentLocationText.value = '未定位';
        isLocationSuccess.value = false;
        _setDefaultLocation();
        return false;
      }
      
    } catch (e) {
      developer.log('💥 智能定位异常: $e', name: 'AmapLocationService');
      currentLocationText.value = '未定位';
      isLocationSuccess.value = false;
      _setDefaultLocation();
      return false;
    } finally {
      isLocating.value = false;  // 🔥 无论成功失败都重置状态
      developer.log('🏁 =============== 智能定位结束 ===============', name: 'AmapLocationService');
    }
  }
  
  /// 🔄 重新定位（刷新当前位置）
  Future<bool> refreshLocation({bool showRationale = false}) async {
    return await smartLocation(
      forceRefresh: true,
      showRationale: showRationale,
    );
  }
  
  // ==================== 📊 位置信息获取方法（供外部使用） ====================
  
  /// 获取当前位置文本（用于UI显示）
  String get locationText => currentLocationText.value;
  
  /// 获取当前纬度
  double get latitude => currentLatitude.value;
  
  /// 获取当前经度
  double get longitude => currentLongitude.value;
  
  /// 定位是否成功
  bool get isSuccess => isLocationSuccess.value;
  
  /// 是否正在定位
  bool get isLocatingNow => isLocating.value;
  
  /// 获取简短地址（城市+区县）
  String getShortAddress() {
    final result = lastLocationResult.value;
    if (result == null || !result.success) {
      return currentLocationText.value;
    }
    
    String displayAddress = '';
    if (result.city != null && result.district != null) {
      displayAddress = '${result.city}${result.district}';
    } else if (result.city != null) {
      displayAddress = result.city!;
    } else if (result.address != null && result.address!.isNotEmpty) {
      displayAddress = result.address!.length > 20 
          ? '${result.address!.substring(0, 20)}...' 
          : result.address!;
    } else {
      displayAddress = '位置信息不详';
    }
    
    return displayAddress;
  }
  
  /// 🎯 手动更新位置信息（从地图页面返回时调用）
  /// 
  /// [address] 位置名称/地址
  /// [latitude] 纬度
  /// [longitude] 经度
  Future<void> updateLocationManually({
    required String address,
    required double latitude,
    required double longitude,
  }) async {
    developer.log('🎯 =============== 手动更新位置信息 ===============', name: 'AmapLocationService');
    developer.log('📍 新位置: $address', name: 'AmapLocationService');
    developer.log('📍 新坐标: $latitude, $longitude', name: 'AmapLocationService');
    
    // 更新位置信息
    currentLocationText.value = address;
    currentLatitude.value = latitude;
    currentLongitude.value = longitude;
    isLocationSuccess.value = true;
    
    // 创建一个临时的定位结果对象
    lastLocationResult.value = AmapLocationResult(
      success: true,
      latitude: latitude,
      longitude: longitude,
      address: address,
      city: null, // 从地图选择的位置可能没有详细信息
      district: null,
    );
    
    await _persistLocationToStorage(
      latitude: latitude,
      longitude: longitude,
      displayAddress: address,
    );
    
    developer.log('✅ 位置信息已手动更新', name: 'AmapLocationService');
    developer.log('🏁 ===============================================', name: 'AmapLocationService');
  }
  
  bool _restoreCachedLocation() {
    if (_storageService == null) {
      return false;
    }
    
    if (!_storageService!.isInitialized) {
      developer.log('ℹ️ StorageService 未初始化，跳过缓存恢复', name: 'AmapLocationService');
      return false;
    }
    
    try {
      final cachedLat = _storageService!.getString(_latitudeStorageKey);
      final cachedLng = _storageService!.getString(_longitudeStorageKey);
      final cachedText = _storageService!.getString(_locationTextStorageKey);
      
      if (cachedLat == null || cachedLng == null) {
        developer.log('ℹ️ 未找到缓存的位置信息', name: 'AmapLocationService');
        return false;
      }
      
      final restoredLatitude = double.tryParse(cachedLat);
      final restoredLongitude = double.tryParse(cachedLng);
      
      if (restoredLatitude == null || restoredLongitude == null) {
        developer.log('⚠️ 缓存的位置信息格式错误', name: 'AmapLocationService');
        return false;
      }
      
      currentLatitude.value = restoredLatitude;
      currentLongitude.value = restoredLongitude;
      currentLocationText.value = cachedText ?? '历史定位';
      isLocationSuccess.value = true;
      lastLocationResult.value = AmapLocationResult(
        success: true,
        latitude: restoredLatitude,
        longitude: restoredLongitude,
        address: cachedText,
      );
      
      developer.log(
        '📦 已恢复缓存的位置信息: $currentLocationText ($restoredLatitude, $restoredLongitude)',
        name: 'AmapLocationService',
      );
      return true;
    } catch (e) {
      developer.log('💥 恢复缓存位置信息失败: $e', name: 'AmapLocationService');
      return false;
    }
  }
  
  Future<void> _persistLocationToStorage({
    required double latitude,
    required double longitude,
    required String displayAddress,
  }) async {
    if (_storageService == null) {
      return;
    }
    
    if (!_storageService!.isInitialized) {
      developer.log('ℹ️ StorageService 未初始化，跳过缓存位置信息', name: 'AmapLocationService');
      return;
    }
    
    try {
      await _storageService!.setString(_latitudeStorageKey, latitude.toString());
      await _storageService!.setString(_longitudeStorageKey, longitude.toString());
      await _storageService!.setString(_locationTextStorageKey, displayAddress);
      developer.log('💾 已缓存当前位置信息', name: 'AmapLocationService');
    } catch (e) {
      developer.log('💥 缓存位置信息失败: $e', name: 'AmapLocationService');
    }
  }
  
  // ==================== 🏠 默认位置管理 ====================
  
  /// 设置默认位置
  void _setDefaultLocation() {
    developer.log('🏠 设置默认位置', name: 'AmapLocationService');
    
    currentLocationText.value = defaultCityName;
    currentLatitude.value = defaultLatitude;
    currentLongitude.value = defaultLongitude;
    isLocationSuccess.value = false;
    
    developer.log('📍 默认位置: $defaultCityName ($defaultLatitude, $defaultLongitude)', name: 'AmapLocationService');
  }
  
  /// 从定位结果更新位置信息
  Future<void> _updateLocationFromResult(AmapLocationResult result) async {
    developer.log('📊 更新位置信息', name: 'AmapLocationService');
    
    // 更新坐标
    if (result.latitude != null && result.longitude != null) {
      currentLatitude.value = result.latitude!;
      currentLongitude.value = result.longitude!;
      developer.log('📍 坐标: ${result.latitude}, ${result.longitude}', name: 'AmapLocationService');
    }
    
    // 更新地址文本（优先使用城市+区县）
    String displayAddress = '';
    if (result.city != null && result.district != null) {
      displayAddress = '${result.city}${result.district}';
    } else if (result.city != null) {
      displayAddress = result.city!;
    } else if (result.address != null && result.address!.isNotEmpty) {
      displayAddress = result.address!.length > 20 
          ? '${result.address!.substring(0, 20)}...' 
          : result.address!;
    } else {
      displayAddress = '位置信息不详';
    }
    
    currentLocationText.value = displayAddress;
    isLocationSuccess.value = true;
    lastLocationResult.value = result;
    
    developer.log('✅ 位置信息已更新: $displayAddress', name: 'AmapLocationService');
    developer.log('🎯 精度: ${result.accuracy}m', name: 'AmapLocationService');
    
    await _persistLocationToStorage(
      latitude: currentLatitude.value,
      longitude: currentLongitude.value,
      displayAddress: displayAddress,
    );
  }

  // ==================== 🗺️ 原生定位方法 ====================

  /// 开始定位（原生方法）
  /// 
  /// [isOnceLocation] 是否单次定位，默认true
  /// [timeout] 定位超时时间
  Future<AmapLocationResult?> startLocation({
    bool isOnceLocation = true,
    Duration? timeout,
  }) async {
    try {
      developer.log('🎯 =============== 开始原生定位 ===============', name: 'AmapLocationService');
      developer.log('📍 定位模式: ${isOnceLocation ? "单次定位" : "持续定位"}', name: 'AmapLocationService');
      developer.log('⏱️ 超时时间: ${timeout?.inSeconds ?? 30}秒', name: 'AmapLocationService');

      // 🔒 内部预检查定位权限（不弹框，静默检查）
      developer.log('🔒 内部预检查定位权限...', name: 'AmapLocationService');
      final hasPermissions = await checkLocationPermissions();
      if (!hasPermissions) {
        developer.log('❌ 定位权限检查失败，无法开始定位', name: 'AmapLocationService');
        return AmapLocationResult(
          success: false,
          errorCode: 12,
          errorMessage: '缺少定位权限',
        );
      }
      developer.log('✅ 权限检查通过，继续执行定位', name: 'AmapLocationService');
      
      // 调用原生定位方法
      final Map<String, dynamic> arguments = {
        'isOnceLocation': isOnceLocation,
      };
      
      developer.log('📞 调用原生定位方法，参数: $arguments', name: 'AmapLocationService');
      
      // 设置超时时间
      final locationFuture = _channel.invokeMethod('startLocation', arguments);
      final timeoutFuture = timeout != null 
          ? Future.delayed(timeout, () => throw TimeoutException('定位超时', timeout))
          : locationFuture;
      
      final result = await Future.any([locationFuture, timeoutFuture]);
      developer.log('📨 定位结果: $result', name: 'AmapLocationService');
      
      Map<String, dynamic>? resultMap;
      
      if (result is Map<String, dynamic>) {
        resultMap = result;
      } else if (result is Map) {
        resultMap = Map<String, dynamic>.from(result);
      }
      
      if (resultMap != null) {
        final locationResult = AmapLocationResult.fromMap(resultMap);
        
        if (locationResult.success) {
          isLocationStarted.value = true;
          developer.log('✅ 原生定位成功!', name: 'AmapLocationService');
          developer.log('📍 坐标: ${locationResult.latitude}, ${locationResult.longitude}', name: 'AmapLocationService');
          developer.log('🎯 精度: ${locationResult.accuracy}m', name: 'AmapLocationService');
          developer.log('📍 地址: ${locationResult.address}', name: 'AmapLocationService');
        } else {
          developer.log('❌ 原生定位失败: ${locationResult.errorMessage} (${locationResult.errorCode})', name: 'AmapLocationService');
        }
        
        return locationResult;
      } else {
        developer.log('❌ 定位返回数据格式错误', name: 'AmapLocationService');
        return AmapLocationResult(
          success: false,
          errorCode: -1,
          errorMessage: '定位返回数据格式错误',
        );
      }
      
    } on TimeoutException catch (e) {
      developer.log('⏱️ 定位超时: ${e.message}', name: 'AmapLocationService');
      return AmapLocationResult(
        success: false,
        errorCode: -2,
        errorMessage: '定位超时',
      );
    } on PlatformException catch (e) {
      developer.log('💥 Platform异常: ${e.message}', name: 'AmapLocationService');
      return AmapLocationResult(
        success: false,
        errorCode: int.tryParse(e.code) ?? -3,
        errorMessage: e.message ?? 'Platform调用异常',
      );
    } catch (e) {
      developer.log('💥 定位异常: $e', name: 'AmapLocationService');
      return AmapLocationResult(
        success: false,
        errorCode: -4,
        errorMessage: '定位异常: $e',
      );
    } finally {
      // 🔥 不在这里重置 isLocating，由 smartLocation 统一管理
      developer.log('🏁 =============== 原生定位结束 ===============', name: 'AmapLocationService');
    }
  }

  /// 停止定位
  Future<bool> stopLocation() async {
    try {
      developer.log('🛑 停止高德定位', name: 'AmapLocationService');
      
      final result = await _channel.invokeMethod('stopLocation');
      
      if (result is Map<String, dynamic> && result['success'] == true) {
        isLocationStarted.value = false;
        isLocating.value = false;
        developer.log('✅ 高德定位已停止', name: 'AmapLocationService');
        return true;
      }
      
      return false;
    } catch (e) {
      developer.log('💥 停止定位异常: $e', name: 'AmapLocationService');
      return false;
    }
  }

  /// 检查定位权限状态（内部使用，不弹框）
  Future<bool> checkLocationPermissions() async {
    try {
      developer.log('🔍 检查定位权限状态...', name: 'AmapLocationService');
      
      final result = await _channel.invokeMethod('checkPermissions');
      
      if (result is Map<String, dynamic>) {
        final hasPermissions = result['hasPermissions'] ?? false;
        developer.log('📋 权限检查结果: $hasPermissions', name: 'AmapLocationService');
        return hasPermissions;
      } else if (result is Map) {
        final resultMap = Map<String, dynamic>.from(result);
        final hasPermissions = resultMap['hasPermissions'] ?? false;
        developer.log('📋 权限检查结果: $hasPermissions', name: 'AmapLocationService');
        return hasPermissions;
      } else if (result is bool) {
        developer.log('📋 权限检查结果: $result', name: 'AmapLocationService');
        return result;
      }
      
      return false;
    } catch (e) {
      developer.log('💥 检查定位权限异常: $e', name: 'AmapLocationService');
      return false;
    }
  }

  /// 逆地理编码：根据坐标获取详细地址信息
  Future<AmapLocationResult?> reverseGeocode(
    double latitude, 
    double longitude, {
    Duration timeout = const Duration(seconds: 10),
  }) async {
    try {
      developer.log('🌐 =============== 开始逆地理编码 ===============', name: 'AmapLocationService');
      developer.log('📍 目标坐标: $latitude, $longitude', name: 'AmapLocationService');
      
      // 参数验证
      if (latitude.isNaN || longitude.isNaN || 
          latitude < -90 || latitude > 90 || 
          longitude < -180 || longitude > 180) {
        developer.log('❌ 坐标参数无效', name: 'AmapLocationService');
        return AmapLocationResult(
          success: false,
          errorCode: -1,
          errorMessage: '坐标参数无效',
        );
      }

      // 预检查权限（内部检查，不弹框）
      final hasPermissions = await checkLocationPermissions();
      if (!hasPermissions) {
        developer.log('❌ 逆地理编码权限检查失败', name: 'AmapLocationService');
        return AmapLocationResult(
          success: false,
          errorCode: 12,
          errorMessage: '缺少定位权限，无法进行逆地理编码',
        );
      }
      
      // 调用原生逆地理编码方法
      final Map<String, dynamic> arguments = {
        'latitude': latitude,
        'longitude': longitude,
      };
      
      developer.log('📞 调用逆地理编码方法，参数: $arguments', name: 'AmapLocationService');
      
      final geocodingFuture = _channel.invokeMethod('reverseGeocode', arguments);
      final timeoutFuture = Future.delayed(timeout, () => throw TimeoutException('逆地理编码超时', timeout));
      
      final result = await Future.any([geocodingFuture, timeoutFuture]);
      developer.log('📨 逆地理编码结果: $result', name: 'AmapLocationService');
      
      Map<String, dynamic>? resultMap;
      
      if (result is Map<String, dynamic>) {
        resultMap = result;
      } else if (result is Map) {
        resultMap = Map<String, dynamic>.from(result);
      }
      
      if (resultMap != null) {
        final geocodeResult = AmapLocationResult.fromMap(resultMap);
        
        if (geocodeResult.success) {
          developer.log('✅ 逆地理编码成功: ${geocodeResult.address}', name: 'AmapLocationService');
        } else {
          developer.log('❌ 逆地理编码失败: ${geocodeResult.errorMessage}', name: 'AmapLocationService');
        }
        
        return geocodeResult;
      }
      
      return null;
    } on TimeoutException {
      developer.log('⏱️ 逆地理编码超时', name: 'AmapLocationService');
      return AmapLocationResult(
        success: false,
        errorCode: -2,
        errorMessage: '逆地理编码超时',
      );
    } catch (e) {
      developer.log('💥 逆地理编码异常: $e', name: 'AmapLocationService');
      return AmapLocationResult(
        success: false,
        errorCode: -4,
        errorMessage: '逆地理编码异常: $e',
      );
    } finally {
      developer.log('🏁 =============== 逆地理编码结束 ===============', name: 'AmapLocationService');
    }
  }

  /// 格式化地址信息
  String formatAddress(String? address) {
    if (address == null || address.isEmpty) {
      return '位置信息不详';
    }
    
    return address.length > 50 ? '${address.substring(0, 50)}...' : address;
  }

  /// 获取精度描述
  String getAccuracyDescription(double? accuracy) {
    if (accuracy == null) return '精度未知';
    
    if (accuracy <= 5) {
      return '高精度';
    } else if (accuracy <= 20) {
      return '中等精度';
    } else if (accuracy <= 100) {
      return '低精度';
    } else {
      return '精度较差';
    }
  }

  /// 快速获取当前位置（原生方法）
  Future<AmapLocationResult?> getCurrentLocation({
    Duration timeout = const Duration(seconds: 10),
  }) async {
    return await startLocation(
      isOnceLocation: true,
      timeout: timeout,
    );
  }

  /// 检查定位结果是否有效
  bool isLocationValid(AmapLocationResult? result) {
    if (result == null || !result.success) return false;
    
    final lat = result.latitude;
    final lng = result.longitude;
    
    if (lat == null || lng == null) return false;
    
    // 检查坐标是否在中国境内（粗略检查）
    if (lat < 3.86 || lat > 53.55 || lng < 73.66 || lng > 135.05) {
      return false;
    }
    
    return true;
  }
}

/// TimeoutException
class TimeoutException implements Exception {
  final String message;
  final Duration? duration;
  
  TimeoutException(this.message, [this.duration]);
  
  @override
  String toString() => 'TimeoutException: $message${duration != null ? " (${duration!.inSeconds}s)" : ""}';
}
